home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / os2 / octa209s.zip / octave-2.09 / scripts / polynomial / polyfit.m < prev    next >
Text File  |  1997-07-10  |  2KB  |  75 lines

  1. ## Copyright (C) 1996 John W. Eaton
  2. ##
  3. ## This file is part of Octave.
  4. ##
  5. ## Octave is free software; you can redistribute it and/or modify it
  6. ## under the terms of the GNU General Public License as published by
  7. ## the Free Software Foundation; either version 2, or (at your option)
  8. ## any later version.
  9. ##
  10. ## Octave is distributed in the hope that it will be useful, but
  11. ## WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13. ## General Public License for more details.
  14. ##
  15. ## You should have received a copy of the GNU General Public License
  16. ## along with Octave; see the file COPYING.  If not, write to the Free
  17. ## Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  18. ## 02111-1307, USA.
  19.  
  20. ## usage:  [p, yf] = polyfit (x, y, n)
  21. ##
  22. ## Returns the coefficients of a polynomial p(x) of degree n that
  23. ## minimizes sumsq (p(x(i)) - y(i)), i.e., that best fits the data
  24. ## in the least squares sense.
  25. ##
  26. ## If two outputs are requested, also return the values of the
  27. ## polynomial for each value of x.
  28.  
  29. ## Author: KH <Kurt.Hornik@ci.tuwien.ac.at>
  30. ## Created: 13 December 1994
  31. ## Adapted-By: jwe
  32.  
  33. function [p, yf] = polyfit (x, y, n)
  34.  
  35.  
  36.   if (nargin != 3)
  37.     usage ("polyfit (x, y, n)");
  38.   endif
  39.  
  40.   if (! (is_vector (x) && is_vector (y) && size (x) == size (y)))
  41.     error ("polyfit: x and y must be vectors of the same size");
  42.   endif
  43.  
  44.   if (! (is_scalar (n) && n >= 0 && ! isinf (n) && n == round (n)))
  45.     error ("polyfit: n must be a nonnegative integer");
  46.   endif
  47.  
  48.   l = length (x);
  49.   x = reshape (x, l, 1);
  50.   y = reshape (y, l, 1);
  51.  
  52.   ## Unfortunately, the economy QR factorization doesn't really save
  53.   ## memory doing the computation -- the returned values are just
  54.   ## smaller.
  55.  
  56.   ## [Q, R] = qr (X, 0);
  57.   ## p = flipud (R \ (Q' * y));
  58.  
  59.   ## XXX FIXME XXX -- this is probably not so good for extreme values of
  60.   ## N or X...
  61.  
  62.   X = (x * ones (1, n+1)) .^ (ones (l, 1) * (0 : n));
  63.  
  64.   p = flipud ((X' * X) \ (X' * y));
  65.  
  66.   if (! prefer_column_vectors)
  67.     p = p';
  68.   endif
  69.  
  70.   if (nargout == 2)
  71.     yf = X * p;
  72.   endif
  73.  
  74. endfunction
  75.